<?php

namespace App\Trip\Train\Order\Impl;

use App\Models\Train\TrainOrders\TrainOrder;
use App\Trip\Train\Order\Interfaces\OrderCancelInterface;
use App\Trip\Train\Order\OrderCancelResult;
use App\Trip\Train\Providers\PiaoChi\TrainOrderService;
use Exception;
use Illuminate\Support\Facades\Log;

class PiaoChiOrderCancelImpl implements OrderCancelInterface
{

    private TrainOrder        $order;
    private TrainOrderService $order_service;
    private int               $retry_count = 0;

    public function __construct(TrainOrder $order)
    {
        $this->order         = $order;
        $this->order_service = new TrainOrderService();
    }

    /**
     * @throws Exception
     */
    public function cancel(): OrderCancelResult
    {
        if (!$this->order->canCancel()) {
            Log::error("订单:{$this->order->getOrderSn()},不可取消,ost:{$this->order->getOrderState()},osst:{$this->order->getOrderSnapState()}");
            return new OrderCancelResult(-1, '订单不可取消');
        }

        /**
         * 当前能取消订单的只有 抢票业务
         */
        if (!$this->order->isSnapUp()) {
            return new OrderCancelResult(-1, '目前只有抢票订单才能取消订单');
        }

        $out_order_id = $this->order->getOutOrderId();
        if (!$out_order_id) {
            return new OrderCancelResult(-1, '订单未下单,无法取消');
        }

        $res = $this->order_service->trainOrderCancel($out_order_id);
        if (!isset($res['status'])) {
            throw new Exception("出票结果确认中，暂无法取消，请稍后");
        }
        $res_str = json_encode($res, JSON_UNESCAPED_UNICODE);
        Log::info("piaochi Order cancelled:{$out_order_id},res ".$res_str);
        return new OrderCancelResult($res['status'], '');
    }
}